<template>
    <div class="tag">
      <el-tag :key="tag.name" v-for="(tag, index) in tags"
      :closable="tag.name !== 'home'"
      :disable-transitions="false"
      :effect="isChecked(tag) ? 'dark' : 'plain'"
      @click="changMenu(tag)"
      @close="handleClose(tag, index)">
        {{tag.label}}
      </el-tag>
    </div>
  </template>
  
  <script setup>
  import { useRoute, useRouter } from 'vue-router'
  import { useStore } from 'vuex'
  
  const store = useStore()
  const router = useRouter()
  const route = useRoute()
  
  const tags = store.state.tabsList
  
  const changMenu = (item) => {
    // console.log(route.path, item.path)
    router.push({
      path: item.path
    })
  }
  
  const isChecked = (item) => {
    const rpath = trimChar(route.path, '/')
    const ipath = trimChar(item.path, '/')
    // console.log(rpath, ipath)
    return rpath === ipath
  }
  
  const handleClose = (item, index) => {
    const length = tags.length - 1
    store.commit('closeTab', item)
    if (item.name !== route.name) {
      return
    }
  
    if (index === length) {
      router.push({
        path: tags[index - 1].path
      })
    } else {
      router.push({
        path: tags[index].path
      })
    }
  }
  
  function trimChar (str, char) {
    if (typeof str === 'undefined') {
      return str
    }
    const regExp = new RegExp(`^${char}+|${char}+$`, 'g')
    return str.replace(regExp, '')
  }
  
  </script>
  
  <style lang="less" scoped>
  .tag{
    margin: 20px;
    width: 100%;
    .el-tag{
      margin-right: 20px;
      cursor: pointer;
    }
  }
  </style>
  